package com.tbit.main.controller;


import cn.hutool.core.collection.CollUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.main.constant.OperateLog;
import com.tbit.main.constant.RedisConstant;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.AccountConfig;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.AccountUserBound;
import com.tbit.main.pojo.RoleConfig;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import com.tbit.main.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 电量额度配置
 *
 * @author Leon
 * 2019年11月13日 下午3:49:25
 */
@Slf4j
@RestController
@RequestMapping("/powerConfig")
public class PowerConfigController {
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private RoleConfigService roleConfigService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private RedisService redisService;

    /**
     * 根据区域id获取
     */
    @RequestMapping("/getByAccountId")
    public JsonResult getByAccountId(Integer accountId) {

        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        AccountConfig accountConfig = accountConfigService.getByAccountId(accountId);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("accountId", accountId);

        if (accountConfig == null) {
            result.put("socLimit", 50);
            result.put("socLimitIsValid", 50);
        } else {
            result.put("socLimit", accountConfig.getSocLimit());
            result.put("socLimitIsValid", accountConfig.getSocLimitIsValid());
            result.put("rideTime", accountConfig.getRideTime());
            result.put("ride", accountConfig.getRide());
            result.put("rideDistance", accountConfig.getRideDistance());
            result.put("logTime", accountConfig.getLogTime());
        }

        return JsonResult.succ(result);
    }

    /**
     * 更新
     */
    @RequestMapping("/update")
    @OperateLog(module = ModuleEnum.POWERCONFIG, methods = MethodEnum.POWERCONFIG_ADD)
    public JsonResult update(AccountConfig accountConfig) {

        Assert.notNull(accountConfig.getAccountId(), "AccountUser.agentId.notNull");

        if (accountConfig.getSocLimit() == null && accountConfig.getSocLimitIsValid() == null) {
            throw new BaseException("Machine.control.paramValue.notNull");
        }

        if (accountConfig.getSocLimitIsValid() != null) {
            if (accountConfig.getSocLimit() == null) {
                AccountConfig accountConfigDB = accountConfigService.getByAccountId(accountConfig.getAccountId());
                accountConfig.setSocLimit(accountConfigDB.getSocLimit());
            }

            if (accountConfig.getSocLimitIsValid() < accountConfig.getSocLimit()) {
                throw new BaseException("Machine.power.socThanIsValid");
            }
        }

        accountConfigService.update(accountConfig);
        LogUtil.info("修改运营区域配置,人员：" + LoginUserContextHolder.getLoginUserId() + ",配置：" + accountConfig);

        List<RoleConfig> roleConfigs = roleConfigService.getParamValue("lookBattery", 1);
        if (CollUtil.isNotEmpty(roleConfigs)) {
            for (RoleConfig roleConfig : roleConfigs) {
                List<AccountUser> accountUserMainMans = accountUserService.getByAccountUserType(new AccountUserBound(accountConfig.getAccountId(), roleConfig.getRoleId()));
                if (CollUtil.isNotEmpty(accountUserMainMans)) {
                    for (AccountUser accountUser1 : accountUserMainMans) {
                        String userKey = RedisConstant.REDIS_ACCOUNT_USER_TOKEN_LIST + accountUser1.getAccountType() + "." + accountUser1.getAccountUserId();
                        List<String> tokens = new LinkedList<>();
                        try {
                            tokens = redisService.getList(userKey);
                        } catch (SerializationException e) {
                            log.error(e.getMessage(), e);
                            redisService.del(userKey);
                        }

                        for (String tokenD : tokens) {
                            redisService.del(tokenD);
                        }
                        redisService.del(userKey);
                    }
                }
            }
        }

        return JsonResult.succ();
    }

}